/*
 * @(#)PathUtils.java $version 2013. 11. 29.
 *
 * Copyright 2007 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.i2.june.dependency.model;

import java.io.File;
import java.io.IOException;

/**
 * @author kimseongjune@nhn.com
 */
public class WebResourcePathUtils {
	public static boolean isWebResourceAbsolutePath(String path) {
		return path.replaceAll(" ", "").startsWith("/");
	}
	
	public static String convertWebResourceAbsolutePathToRealAbsolutePath(String contextPath, String webResourceAbsolutePath) throws IOException {
		File file = new File(contextPath + webResourceAbsolutePath);
		
		return file.getCanonicalPath();
	}
	
	public static boolean isValidAbsolutePath(String path) {
		File file = new File(path);
		
		return file.exists() && file.isAbsolute();
	}

	public static String makeAbsolutePath(String relativePath, String absolutePath) throws Exception {
		if (WebResourcePathUtils.isValidAbsolutePath(relativePath)) {
			return new File(relativePath).getCanonicalPath();
		}
		
		if (!WebResourcePathUtils.isValidAbsolutePath(absolutePath)) {
			throw new IllegalArgumentException(absolutePath + " is not absolute path.");
		}
		
		File baseFile = new File(absolutePath);
		String basedPath;
		
		if (baseFile.exists() && baseFile.isDirectory()) {
			basedPath = baseFile.getAbsolutePath();
		} else {
			basedPath = baseFile.getParent();
		}
		
		String pathname = basedPath + File.separator + relativePath;
		String canonicalPath = new File(pathname).getCanonicalPath();
		return canonicalPath;
	}

}
